﻿using InteractiveDataDisplay.WPF;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace LineGraphSample
{
    [AddINotifyPropertyChangedInterface]
    public class RandomViewModel
    {
        public string ButtonText { get; set; } = "开始";
        private LineGraph LineGraph = null;
        public RandomViewModel(LineGraph _lineGraph)
        {
            LineGraph = _lineGraph;

            LineGraph.Stroke = (Brush)new BrushConverter().ConvertFromString("blue");
            LineGraph.StrokeThickness = 1;

            LineGraph.Unloaded += (s, e) =>
            {
                timer?.Stop();
                timer?.Dispose();
                LineGraph = null;
            };
        }

        public bool IsRunning { get; set; } = false;

        private DelegateCommand _RandomRunCommand;
        public DelegateCommand RandomRunCommand => _RandomRunCommand = new DelegateCommand(ActionRandomRun);
        private System.Timers.Timer timer;
        private int index = 0;
        private void ActionRandomRun()
        {
            if (IsRunning)
            {
                timer.Stop();
                IsRunning = false;
                ButtonText = "开始";
            }
            else
            {
                if (timer == null)
                {
                    timer = new System.Timers.Timer(10);
                    timer.Elapsed += Timer_Elapsed;
                }
                timer.Start();
                ButtonText = "停止";
            }
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (LineGraph != null)
            {
                IsRunning = true;

                double x = index / 10;
                ArrayX.Add(x);

                float fre = 0.1f;
                double y = Math.Sin(x * Math.PI * 2 * fre);

                ArrayY.Add(y);

                LineGraph.Dispatcher.Invoke(() =>
                {
                    this.LineGraph.Plot(ArrayX, ArrayY);
                });

                //System.Diagnostics.Debug.Print($"ArrayX Length:{ArrayX.Count}");

                if (ArrayX.Count >= maxLength)
                {
                    ArrayX.RemoveAt(0);
                }

                if (ArrayY.Count >= maxLength)
                {
                    ArrayY.RemoveAt(0);
                }


                index++;
            }
        }

        private int maxLength = 100;
        private List<double> ArrayX = new List<double>();
        private List<double> ArrayY = new List<double>();
    }
}
